package org.linlinjava.litemall.db.service;

import static org.linlinjava.litemall.db.domain.constants.WithdrawStatus.PENDING;
import static org.linlinjava.litemall.db.domain.constants.WithdrawStatus.REFUND;
import static org.linlinjava.litemall.db.domain.constants.WithdrawStatus.SUCCESS;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import javax.annotation.Resource;
import org.linlinjava.litemall.db.dao.LitemallWithdrawMapper;
import org.linlinjava.litemall.db.domain.LitemallWithdraw;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LitemallWithdrawService {
  @Resource
  private LitemallWithdrawMapper withdrawMapper;

  @Resource
  private LitemallAccountService accountService;

  public LitemallWithdraw findById(Integer id) {
    return withdrawMapper.selectByPrimaryKey(id);
  }

  private void update(LitemallWithdraw withdraw) {
    withdraw.setUpdateTime(LocalDateTime.now());
    withdrawMapper.updateByPrimaryKeySelective(withdraw);
  }

  @Transactional
  LitemallWithdraw add(Integer accountId, BigDecimal amount) {
    LitemallWithdraw withdraw = new LitemallWithdraw();
    withdraw.setUpdateTime(LocalDateTime.now());
    withdraw.setCreateTime(LocalDateTime.now());
    withdraw.setAccountId(accountId);
    withdraw.setAmount(amount);
    withdraw.setStatus(PENDING);
    withdrawMapper.insert(withdraw);
    accountService.withdraw(accountId, withdraw.getId().toString(), amount);
    return withdraw;
  }

  @Transactional
  public void success(Integer id, String remark) {
    LitemallWithdraw withdraw = findById(id);
    if (withdraw.getStatus() == SUCCESS) {
      throw new RuntimeException("提现已经退款");
    }
    if (withdraw.getStatus() == REFUND) {
      throw new RuntimeException("提现已经成功");
    }
    withdraw.setStatus(SUCCESS);
    withdraw.setRemark(remark);
    update(withdraw);
  }

  @Transactional
  public void fail(Integer id, String remark) {
    LitemallWithdraw withdraw = findById(id);
    if (withdraw.getStatus() == SUCCESS) {
      throw new RuntimeException("提现已经退款");
    }
    if (withdraw.getStatus() == REFUND) {
      throw new RuntimeException("提现已经成功");
    }
    withdraw.setStatus(REFUND);
    withdraw.setRemark(remark);
    update(withdraw);

    accountService.refund(//
        withdraw.getAccountId(), remark, withdraw.getId().toString(), withdraw.getAmount()//
    );
  }
}
